<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>

<body>
    <h1>创建axios实例</h1>
    <button id="btn">点击</button>

    <script>
        const oBtn = document.getElementById('btn');
        //创建 axios 的实例
        const creatorAxios = axios.create({
            baseURL: '/',
            timeout: 10000,
            header: {}
        });

        //添加请求拦截器
        creatorAxios.interceptors.request.use((config) => {
            //给请求头添加 token 属性 并赋值
            const token = 'asdada.asfffdg.resdfds'
            config.headers.token = token;

            return config;
        }, (err) => {
            return Promise.reject(err)
        })
        //添加响应拦截器
        creatorAxios.interceptors.response.use((config) => {
            // 处理拿到的结果
            if(config.data.code !== 10000){
                return Promise.reject(config.data.msg)
            }

            return config.data.data
        }, (err) => {
            return Promise.reject(err)
        })



        oBtn.onclick = async function () {
            try {
                const re = await creatorAxios.get('/user', {
                    params: {
                        userId: '001'
                    }
                })
                console.log(re);
            } catch (e) {
                console.log('e',e);
            }
        }
    </script>
</body>

</html>